<template>
  <el-card class="box-card">

    <!--  新增/修改弹出框  -->
    <el-dialog
        @opened="handleBeforeOpen"
        :title="dialogTitle+'相册'"
        :visible.sync="dialogAddOrUpdate"
        width="40%"
        :before-close="handleCloseAdd">
      <el-form :model="albumForm" :rules="albumFormRules" ref="albumForm" label-width="100px">

        <el-form-item label="相册封面" prop="cover">
          <my-upload-img ref="upload"
                          @file-selected="handleFileSelected"
                          @image-removed="handleImageRemoved"
                          :imageUrl="albumForm.cover"
          />
        </el-form-item>

        <el-form-item label="相册名称" prop="name">
          <el-input v-model="albumForm.name"></el-input>
        </el-form-item>

        <el-form-item label="相册描述" prop="desc">
          <el-input v-model="albumForm.desc"></el-input>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="albumForm.status">
            <el-radio :label=0>禁用</el-radio>
            <el-radio :label=1>启用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitAddOrUpdateForm('albumForm')">立即{{ dialogTitle }}</el-button>
          <el-button @click="resetForm('albumForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


    <!--  表格操作  -->
    <div class="select-div">
      <el-form :inline="true" style="height: 40px">

        <el-form-item>
          <my-select v-model="condition.status"
                     placeholder="请选择状态"
                     :showList="condition.statusList"
                     labelName='label'
                     valueName='value'/>
        </el-form-item>

        <el-form-item>
          <el-input
              clearable
              v-model="condition.keywords"
              prefix-icon="el-icon-search"
              size="small"
              placeholder="请输入相册名称关键字"
              style="width:200px"
              @keyup.enter.native="searchAlbums"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" size="small" icon="el-icon-search" style="margin-left:1rem" @click="searchAlbums">
            搜索
          </el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" size="small" icon="el-icon-plus" @click="dialogAdd">新增</el-button>
        </el-form-item>


        <el-form-item>
          <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteCheck()"
                     :disabled="this.selection.length === 0">删除选中
          </el-button>
        </el-form-item>

      </el-form>
    </div>


    <!--  表格内容  -->
    <el-table
        ref="multipleTable"
        :data="tableData"
        border
        :header-cell-style="{'text-align':'center'}"
        :cell-style="{'text-align':'center'}"
        @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>

      <el-table-column prop="cover" label="封面图片">
        <template slot-scope="scope">
          <el-image 
            style="width: 100%;height: 170px" 
            :src="scope.row.cover"
            :preview-src-list="[scope.row.cover]"
          />
        </template>
      </el-table-column>

      <el-table-column prop="name" label="名称" sortable>
        <template slot-scope="scope">
          <el-link type="primary" @click="goPhoto(scope.row)">{{ scope.row.name }}</el-link>
        </template>
      </el-table-column>

      <el-table-column prop="desc" label="描述" sortable></el-table-column>

      <el-table-column prop="countPhoto" label="照片数量" sortable></el-table-column>

      <el-table-column prop="status" label="状态" sortable>
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.status"
              active-text="公开"
              inactive-text="私密"
              :active-value="1"
              :inactive-value="0"
              @change="changeStatus(scope.row.id,scope.row.status)"
          >
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column label="操作" fixed="right" width="100">
        <template slot-scope="scope">
          <el-tooltip effect="dark" content="编辑" placement="top-start">
            <el-button circle icon="el-icon-edit" size="mini" @click="dialogUpdate(scope.row.id)"/>
          </el-tooltip>

          <el-tooltip effect="dark" content="删除" placement="top-start">
            <el-button circle icon="el-icon-delete" size="mini" type="danger"
                       @click="deleteCheck(scope.row.id)"/>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>


    <!--  分页  -->
    <pagination
        :total="total"
        :page_index="pageNum"
        @pageChange="pageChange"
    />

  </el-card>
</template>

<script>
import { albumApi } from '@/api';

export default {
  name: "Album",
  data() {

    return {
      tableData: [],
      selection: [],
      selectedNum: 0,
      albumForm: {},
      total: 0,
      pageNum: 1,
      pageSize: 10,
      dialogAddOrUpdate: false,
      dialogPicture: false,
      dialogTitle: '',
      condition: {
        status: null,
        keywords: null,
        statusList: [
          {
            value: 0,
            label: "私密"
          },
          {
            value: 1,
            label: "公开"
          }
        ]
      },
      albumFormRules: {
        name: [
          {required: true, message: '请输入相册名称', trigger: 'blur'}
        ],
        cover: [
        ],
        desc: [
          {required: true, message: '请输入相册描述', trigger: 'blur'}
        ],
        status: [
          {required: true, message: '请选择状态', trigger: 'change'},
          {
            validator: (rule, value, callback) => {
              if (value !== 0 && value !== 1 && value !== '0' && value !== '1') {
                callback(new Error('请选择状态'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ]
      },
      selectedFile: null
    }
  },

  methods: {
    /**
     * 复选框事件
     * @param selection 选中数据数组
     */
    handleSelectionChange(selection) {
      this.selection = selection.map(item => item.id)
      this.selectedNum = selection.length
    },


    /**
     * 分页回调函数
     * @param val
     */
    pageChange(val) {
      this.pageNum = val.pageNum;
      this.pageSize = val.pageSize;
      this.loadAlbumList();
    },


    /**
     * 搜索框事件
     */
    searchAlbums() {
      this.pageNum = 1;
      this.loadAlbumList();
    },

    /**
     * 新增按钮事件
     */
    dialogAdd() {
      this.dialogTitle = "新增";
      // 确保表单初始化为完整结构，并设置默认值
      this.albumForm = {
        name: '',
        desc: '',
        status: 1, // 默认为启用状态
        cover: ''
      };
      
      // 延迟打开对话框，确保表单已正确初始化
      this.$nextTick(() => {
      this.dialogAddOrUpdate = true;
      });
    },

    /**
     * dialog打开时触发的事件
     */
    handleBeforeOpen() {

    },

    /**
     * 当用户通过点击关闭图标或遮罩关闭 Dialog 时起效的事件
     */
    handleCloseAdd() {
      this.resetForm('albumForm');
      this.dialogAddOrUpdate = false;
    },

    // 重置弹出框内容
    resetForm(formName) {
      console.log('重置表单',formName);
      // 保存cover值用于释放URL
      const coverUrl = this.albumForm.cover;
      
      // 重置表单
      this.$refs[formName].resetFields();
      this.albumForm = {};
      this.selectedFile = null;
      
      // 释放预览URL
      if (coverUrl && coverUrl.startsWith('blob:')) {
        URL.revokeObjectURL(coverUrl);
      }
      
      // 重置上传组件
      if (this.$refs.upload) {
        this.$refs.upload.clearSelection();
      }
    },

    /**
     * 公开/私密
     */
    changeStatus(id, status) {
      this.albumForm.id = id;
      this.albumForm.status = status;
      albumApi.updateAlbum(this.albumForm).then((response) => {
        if (response.data.code === 20000) {
          this.$message.success("修改成功！");
          this.loadAlbumList();
        }
      });
    },

    handleFileSelected(file) {
      this.selectedFile = file;
    },
    handleImageRemoved() {
      this.selectedFile = null;
    },


    /**
     * 提交新增表单
     * @param formName
     */
    submitAddOrUpdateForm(formName) {
      console.log('提交的表单数据:', JSON.stringify(this.albumForm));
      
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 创建FormData对象
          const formData = new FormData();
          
          // 添加表单数据
          formData.append('id', this.albumForm.id || '');
          formData.append('name', this.albumForm.name);
          formData.append('desc', this.albumForm.desc);
          formData.append('status', this.albumForm.status);
          
          // 如果有封面文件，添加到表单数据
          if (this.selectedFile) {
            formData.append('coverFile', this.selectedFile);
          }
          
          // 统一调用API
          const apiMethod = this.albumForm.id ? albumApi.updateAlbum : albumApi.addAlbum;
          
          apiMethod(formData,{
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }).then(response => {
            if (response.data.code === 20000) {
              this.$message.success('操作成功！');
              this.dialogAddOrUpdate = false;
              this.resetForm(formName);
              this.loadAlbumList();
            }
          })
          
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },


    /**
     * 删除数据
     * @param id 数据id
     */
    deleteCheck(id) {
      this.$confirm("删除后不可恢复", "提示", {
        type: "warning"
      }).then(() => {
        const ids = id == null ? this.selection : [id];
        albumApi.deleteAlbums(ids).then((response) => {
          if (response.data.code === 20000) {
            this.$message.success("相册删除成功！");
            this.loadAlbumList();
          }
        });
      }).catch(() => {
        // 取消删除操作
      });
    },


    /**
     * 编辑按钮触发事件
     * @param id 数据id
     */
    dialogUpdate(id) {
      albumApi.getAlbumInfo(id).then((response) => {
        if (response.data.code === 20000) {
          //将当前行角色信息数据回显到弹出表单中，并打开表单
          const data = response.data.data;
          this.albumForm = {
            id: data.id,
            name: data.name,
            desc: data.desc,
            status: data.status,
            cover: data.cover
          };
          this.dialogTitle = "修改";
          this.dialogAddOrUpdate = true;
        }
      });
    },


    /**
     * 手动上传
     * @param param
     */
    upload(param) {
      const formData = new FormData();
      formData.append('file', param.file);
      albumApi.uploadAlbumCover(formData).then(response => {
        if (response.data.code === 20000) {
          this.$message.success('上传成功！');
        }
      });
    },


    /**
     * 获取相册列表
     */
    loadAlbumList() {
      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        status: this.condition.status,
        keywords: this.condition.keywords
      };
      
      albumApi.getAlbumList(params).then((response) => {
        if (response.data.code === 20000) {
          this.tableData = response.data.data?.pagingList || [];
          this.total = response.data.data?.count || 0;
        }
      });
    },


    /**
     * 跳转到照片页面
     */
    goPhoto(row) {
      this.$router.push({path: '/albums/photo', query: {albumId: row.id}})
    }

  },

  created() {
    this.loadAlbumList();
  }
}
</script>

<style scoped>

</style>